package com.attain.controller;

import com.attain.pojo.News;
import com.attain.pojo.User;
import com.attain.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @GetMapping
    public String getAllNews(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        List<News> newsList = newsService.getAllNews();
        model.addAttribute("newsList", newsList);
        return "news";
    }

    @PostMapping
    public String addNews(News news, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        try {
            newsService.addNews(news, user.getId());
            redirectAttributes.addFlashAttribute("message", "添加新闻成功");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/news";
    }

    @GetMapping("/{id}")
    public String getNewsById(@PathVariable Integer id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);
        return "news-detail";
    }

    @PutMapping("/{id}")
    public String updateNews(@PathVariable Integer id, @RequestBody News news, RedirectAttributes redirectAttributes) {
        try {
            news.setId(id);
            newsService.updateNews(news);
            redirectAttributes.addFlashAttribute("message", "更新新闻成功");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/news";
    }

    @DeleteMapping("/{id}")
    public String deleteNews(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            newsService.deleteNews(id);
            redirectAttributes.addFlashAttribute("message", "删除新闻成功");
        } catch (RuntimeException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:/news";
    }
}